package 基础篇.线程同步.非阻塞取钱案例;

/**
 * @author IBM CHEN ZHI KAN
 * @create 2018/7/28
 */
public class DrawThread extends Thread{
  private Account account;
  private double drawAmount;
  public DrawThread(Account account,double drawAmount){
    super();
    this.account=account;
    this.drawAmount=drawAmount;
  }
  public void run(){
    //1.假设有A和B线程同时执行此方法体
    //2.A先运行账户中的钱大于可取的钱，则开始取钱
    //4.此时账户还是原先的钱，并没有被修改，B取钱的金额也小于账户金额，B也开始取钱
    if(account.getBalance() >= drawAmount){
      System.out.println("取钱成功，吐出钞票");
      try{
        //3.A被阻塞，B开始运行
        //5.B被阻塞,A开始运行
        Thread.sleep(1000l);
      }catch (Exception e){
        e.printStackTrace();
      }
      //6.A开始扣钱 1000-600=400
      //7.B开始扣钱 400-600=-200
      account.setBalance(account.getBalance()-drawAmount);
      System.out.println("余额为："+account.getBalance());
    }else{
      System.out.println(getName()+"余额已取完");
    }
  }
}
